import os
from flask import Flask, send_from_directory, render_template, request
from flask_cors import CORS
from config.loggingConf import FlaskLogger
from match import init_db
from utils.token import check_token_type


def create_app():
    app = Flask(
        __name__,
        static_folder="templates/dist",
        template_folder="templates/dist"
    )

    app.secret_key = os.environ.get("FLASK_SECRET_KEY", "a_very_secret_key")

    # 配置
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    app.config.update(
        UPLOAD_FOLDER=os.path.join(BASE_DIR, 'upload'),
        ALLOWED_EXTENSIONS={'xlsx', 'xls'},
        MAX_CONTENT_LENGTH=16 * 1024 * 1024
    )

    init_db()

    # 初始化日志
    FlaskLogger.configure_app_logger(app)

    # 配置跨域
    CORS(
        app,
        resources={
            r"/duizhang/*": {
                "origins": ["*"],
                "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
                "allow_headers": ["Content-Type", "Authorization", "HSToken"]
            }
        },
        supports_credentials=True
    )

    # 注册蓝图
    from controller.SupplierReconciliationController import bp_reconciliation
    app.register_blueprint(bp_reconciliation, url_prefix="/duizhang/api")

    # 前端路由
    @app.route("/")
    def index():
        return render_template("index.html")

    @app.route("/<path:path>")
    def serve(path):

        print(f"✅ 服务启动于端口 {path}")

        # 排除static路径
        if path.startswith('duizhang/static/'):
            return send_from_directory(app.static_folder, path.replace('duizhang/static/', '', 1))

        # 获取 form-data 中的参数
        # tokenStr = request.args.get('Hstoken', type=str)
        # type_param = request.args.get('type', type=int)

        # 验证 type 是否有效，如果提供了 type
        # if type_param is not None and type_param not in [2, 5, 9, 10, 11, 12, 13, 14]:
        #     return render_template('404.html')

        # 验证 token（无论 type 是否存在）
        # if tokenStr is None or tokenStr == '' or not check_token_type(type_param, tokenStr):
        #     return render_template("403.html")

        static_path = os.path.join(app.static_folder, path)
        if path != "" and os.path.exists(static_path):
            return send_from_directory(app.static_folder, path)
        else:
            return send_from_directory(app.template_folder, "index.html")

    return app


def find_available_port(start_port=5000):
    import socket
    port = start_port
    while port < 65535:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            try:
                s.bind(('', port))
                return port
            except OSError:
                port += 1
    raise Exception("未找到可用端口")


if __name__ == '__main__':
    app = create_app()
    try:
        port = find_available_port(5010)
        print(f"✅ 服务启动于端口 {port}")
        app.run(debug=True, host='0.0.0.0', port=port, use_reloader=False)
    except Exception as e:
        print(f"❌ 无法启动服务: {str(e)}")
